package client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import data.User;
import protocal.DataPackage;
import protocal.DataPackage.MessageType;
import excption.ConnectException;


public class IMClient {
	
	private final static Logger logger = LogManager.getLogger(IMClient.class);
	
	private Socket socket;
	
	private ObjectOutputStream objectOutputStream;
	private ObjectInputStream objectInputStream;
	
	
	private static IMClient imClient;
	
	private IMClient() throws UnknownHostException, IOException{
			socket = new Socket("127.0.0.1",8001);
//			10.222.29.159  127.0.0.1
			objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
			objectInputStream = new ObjectInputStream(socket.getInputStream());
	}
	//singoten ? reconnect?
	public static IMClient getInstance() throws ConnectException{
		if (imClient==null) {
			synchronized (IMClient.class) {
				if (imClient==null) {
					try {
						imClient = new IMClient();
					} catch (UnknownHostException e) {
						
						logger.error(e);
						throw new ConnectException("fail to conect server");
//						System.exit(0);
					} catch (IOException e) {
						logger.error(e);
						throw new ConnectException("fail to conect server");
//						System.exit(0);
					}
				}
			}
		}
		return imClient;
	}
	
	
	public ObjectOutputStream getObjectOutputStream() {
		return objectOutputStream;
	}
	public ObjectInputStream getObjectInputStream() {
		return objectInputStream;
	}
	public void close(){
		
		DataPackage dataPackage = new DataPackage();
		dataPackage.setFromeName(User.name);
		dataPackage.setToName("\\");
		dataPackage.setMessageType(MessageType.LOGOUT);
		dataPackage.setTime(new Date().getTime());
		try {
			objectOutputStream.writeObject(dataPackage);
			Thread.sleep(3000);
			objectOutputStream.close();
			objectInputStream.close();
			socket.close();
		} catch (InterruptedException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		}
		
		
	}
	
	
	
	

}
